﻿using AutoMapper;
using QYmall.Core.API.Filters;
using QYmall.Core.Common.Emum;
using QYmall.Core.Common.Extensions;
using QYmall.Core.Common.Helper;
using QYmall.Core.IServices;
using QYmall.Core.Model.Models;
using QYmall.Core.Model.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace QYmall.Core.API.Controllers.Member
{
    /// <summary>
    /// 会员商品收藏
    /// </summary>
    [Route("admin/member/favorite")]
    [ApiController]
    public class MemberFavoriteController : ControllerBase
    {
        private readonly IShopGoodsFavoriteService _shopGoodsFavoriteService;
        private readonly IUserService _userService;
        private readonly IMapper _mapper;

        /// <summary>
        /// 依赖注入
        /// </summary>
        public MemberFavoriteController(IShopGoodsFavoriteService shopGoodsFavoriteService, 
            IUserService userService, IMapper mapper)
        {
            _shopGoodsFavoriteService = shopGoodsFavoriteService;
            _userService = userService;
            _mapper = mapper;
        }

        #region 管理员调用接口==========================
        /// <summary>
        /// 根据ID获取数据
        /// 示例：/admin/member/favorite/1
        /// </summary>
        [HttpGet("{id}")]
        [Authorize]
        [AuthorizeFilter("MemberFavorite", ActionType.View)]
        public async Task<IActionResult> GetById([FromRoute] int id, [FromQuery] BaseParameter param)
        {
            //检测参数是否合法
            if (!param.Fields.IsPropertyExists<ShopGoodsFavoriteDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }
            //查询数据库获取实体
            var model = await _shopGoodsFavoriteService.QueryAsync<ShopGoodsFavorite>(x => x.Id == id, WriteRoRead.Write);
            if (model == null)
            {
                return NotFound(ResponseMessage.Error($"数据{id}不存在或已删除"));
            }
            //使用AutoMapper转换成ViewModel，根据字段进行塑形
            var result = _mapper.Map<ShopGoodsFavoriteDto>(model).ShapeData(param.Fields);
            return Ok(result);
        }

        /// <summary>
        /// 获取指定数量列表
        /// 示例：/admin/member/favorite/view/10
        /// </summary>
        [HttpGet("view/{top}")]
        [Authorize]
        [AuthorizeFilter("MemberFavorite", ActionType.View)]
        public async Task<IActionResult> GetList([FromRoute] int top, [FromQuery] BaseParameter searchParam)
        {
            //检测参数是否合法
            if (searchParam.OrderBy != null
                && !searchParam.OrderBy.Replace("-", "").IsPropertyExists<ShopGoodsFavoriteDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的排序参数"));
            }
            if (!searchParam.Fields.IsPropertyExists<ShopGoodsFavoriteDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }

            //获取数据库列表
            var resultFrom = await _shopGoodsFavoriteService.QueryListAsync<ShopGoodsFavorite>(top,
                x => (!searchParam.Keyword.IsNotNullOrEmpty() || (x.Title != null && x.Title.Contains(searchParam.Keyword))),
                searchParam.OrderBy ?? "-Id");

            //映射成DTO，根据字段进行塑形
            var resultDto = _mapper.Map<IEnumerable<ShopGoodsFavoriteDto>>(resultFrom).ShapeData(searchParam.Fields);
            //返回成功200
            return Ok(resultDto);
        }

        /// <summary>
        /// 获取分页列表
        /// 示例：/admin/member/favorite?pageSize=10&pageIndex=1
        /// </summary>
        [HttpGet]
        [Authorize]
        [AuthorizeFilter("MemberFavorite", ActionType.View)]
        public async Task<IActionResult> GetList([FromQuery] BaseParameter searchParam, [FromQuery] PageParamater pageParam)
        {
            //检测参数是否合法
            if (searchParam.OrderBy != null
                && !searchParam.OrderBy.Replace("-", "").IsPropertyExists<ShopGoodsFavoriteDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的排序参数"));
            }
            if (!searchParam.Fields.IsPropertyExists<ShopGoodsFavoriteDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }

            //获取数据列表，如果ID大于0则查询该用户下所有的列表
            var list = await _shopGoodsFavoriteService.QueryPageAsync(
                pageParam.PageSize,
                pageParam.PageIndex,
                x => (!searchParam.Keyword.IsNotNullOrEmpty() || (x.Title != null && x.Title.Contains(searchParam.Keyword))),
                searchParam.OrderBy ?? "-Id");

            //x-pagination
            var paginationMetadata = new
            {
                totalCount = list.TotalCount,
                pageSize = list.PageSize,
                pageIndex = list.PageIndex,
                totalPages = list.TotalPages
            };
            Response.Headers.Add("x-pagination", SerializeHelper.SerializeObject(paginationMetadata));

            //映射成DTO，根据字段进行塑形
            var resultDto = _mapper.Map<IEnumerable<ShopGoodsFavoriteDto>>(list).ShapeData(searchParam.Fields);
            return Ok(resultDto);
        }

        /// <summary>
        /// 删除一条记录
        /// 示例：/admin/member/favorite/1
        /// </summary>
        [HttpDelete("{id}")]
        [Authorize]
        [AuthorizeFilter("MemberFavorite", ActionType.Delete)]
        public async Task<IActionResult> Delete([FromRoute] int id)
        {
            if (!await _shopGoodsFavoriteService.ExistsAsync<ShopGoodsFavorite>(x => x.Id == id))
            {
                return NotFound(ResponseMessage.Error($"数据{id}不存在或已删除"));
            }
            var result = await _shopGoodsFavoriteService.DeleteAsync(x => x.Id == id);

            return NoContent();
        }

        /// <summary>
        /// 批量删除记录
        /// 示例：/admin/member/favorite?ids=1,2,3
        /// </summary>
        [HttpDelete]
        [Authorize]
        [AuthorizeFilter("MemberFavorite", ActionType.Delete)]
        public async Task<IActionResult> DeleteByIds([FromQuery] string Ids)
        {
            if (Ids == null)
            {
                return BadRequest(ResponseMessage.Error("传输参数不可为空"));
            }

            //将ID列表转换成IEnumerable
            var arrIds = Ids.ToIEnumerable<long>();
            if (arrIds == null)
            {
                return BadRequest(ResponseMessage.Error("传输参数不符合规范"));
            }
            //执行批量删除操作
            await _shopGoodsFavoriteService.DeleteAsync(x => arrIds.Contains(x.Id));

            return NoContent();
        }
        #endregion

        #region 普通账户调用接口========================
        /// <summary>
        /// 根据商品ID获取数据
        /// 示例：/account/member/favorite/goods/1
        /// </summary>
        [HttpGet("/account/member/favorite/goods/{id}")]
        public async Task<IActionResult> GetByGoodsId([FromRoute] int id, [FromQuery] BaseParameter param)
        {
            //检测参数是否合法
            if (!param.Fields.IsPropertyExists<ShopGoodsFavoriteDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            if (userId == 0)
            {
                return NotFound(ResponseMessage.Error("用户尚未登录"));
            }
            //查询数据库获取实体
            var model = await _shopGoodsFavoriteService.QueryAsync(x => x.UserId == userId && x.ShopGoods != null && x.ShopGoods.Id == id);
            if (model == null)
            {
                return NotFound(ResponseMessage.Error($"数据{id}不存在或已删除"));
            }
            //使用AutoMapper转换成ViewModel，根据字段进行塑形
            var result = _mapper.Map<ShopGoodsFavoriteDto>(model).ShapeData(param.Fields);
            return Ok(result);
        }

        /// <summary>
        /// 获取分页列表
        /// 示例：/account/member/favorite?pageSize=10&pageIndex=1
        /// </summary>
        [HttpGet("/account/member/favorite")]
        [Authorize]
        public async Task<IActionResult> AccountGetList([FromQuery] BaseParameter searchParam, [FromQuery] PageParamater pageParam)
        {
            //检测参数是否合法
            if (searchParam.OrderBy != null
                && !searchParam.OrderBy.Replace("-", "").IsPropertyExists<ShopGoodsFavoriteDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的排序参数"));
            }
            if (!searchParam.Fields.IsPropertyExists<ShopGoodsFavoriteDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            if (userId == 0)
            {
                return BadRequest(ResponseMessage.Error("用户尚未登录"));
            }

            //获取数据列表，如果ID大于0则查询该用户下所有的列表
            var list = await _shopGoodsFavoriteService.QueryPageAsync(
                pageParam.PageSize,
                pageParam.PageIndex,
                x => x.UserId == userId
                && (x.ShopGoods != null && x.ShopGoods.Status == 0)
                && (!searchParam.Keyword.IsNotNullOrEmpty() || (x.Title != null && x.Title.Contains(searchParam.Keyword))),
                searchParam.OrderBy ?? "-Id");

            //x-pagination
            var paginationMetadata = new
            {
                totalCount = list.TotalCount,
                pageSize = list.PageSize,
                pageIndex = list.PageIndex,
                totalPages = list.TotalPages
            };
            Response.Headers.Add("x-pagination", SerializeHelper.SerializeObject(paginationMetadata));

            //映射成DTO，根据字段进行塑形
            var resultDto = _mapper.Map<IEnumerable<ShopGoodsFavoriteDto>>(list).ShapeData(searchParam.Fields);
            return Ok(resultDto);
        }

        /// <summary>
        /// 添加一条记录
        /// 示例：/account/member/favorite
        /// </summary>
        [HttpPost("/account/member/favorite")]
        [Authorize]
        public async Task<IActionResult> AccountAdd([FromBody] ShopGoodsFavoriteEditDto modelDto)
        {
            var result = await _shopGoodsFavoriteService.AddAsync(modelDto);
            return Ok(result);
        }

        /// <summary>
        /// 删除一条记录
        /// 示例：/account/member/favorite/1
        /// </summary>
        [HttpDelete("/account/member/favorite/{id}")]
        [Authorize]
        public async Task<IActionResult> AccountDelete([FromRoute] int id)
        {
            if (!await _shopGoodsFavoriteService.ExistsAsync<ShopGoodsFavorite>(x => x.Id == id))
            {
                return NotFound(ResponseMessage.Error($"数据{id}不存在或已删除"));
            }
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            if (userId == 0)
            {
                return BadRequest(ResponseMessage.Error("用户尚未登录"));
            }
            var result = await _shopGoodsFavoriteService.DeleteAsync(x => x.UserId == userId && x.Id == id);

            return NoContent();
        }

        /// <summary>
        /// 批量删除记录
        /// 示例：/account/member/favorite?ids=1,2,3
        /// </summary>
        [HttpDelete("/account/member/favorite")]
        [Authorize]
        public async Task<IActionResult> AccountDeleteByIds([FromQuery] string Ids)
        {
            if (Ids == null)
            {
                return BadRequest(ResponseMessage.Error("传输参数不可为空"));
            }
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            if (userId == 0)
            {
                return BadRequest(ResponseMessage.Error("用户尚未登录"));
            }

            //将ID列表转换成IEnumerable
            var arrIds = Ids.ToIEnumerable<long>();
            if (arrIds == null)
            {
                return BadRequest(ResponseMessage.Error("传输参数不符合规范"));
            }
            //执行批量删除操作
            await _shopGoodsFavoriteService.DeleteAsync(x => x.UserId == userId && arrIds.Contains(x.Id));

            return NoContent();
        }
        #endregion
    }
}
